<template>
  <div class="admin-profile">
    <div class="page-header">
      <h2>个人中心</h2>
    </div>

    <el-card class="profile-card" shadow="never">
      <div class="profile-content">
        <!-- 个人信息展示 -->
        <div class="profile-info" v-if="!isEditing">
          <div class="avatar-section">
            <div class="avatar-wrapper">
              <el-avatar :size="120" :src="avatarUrl || userInfo.avatar" class="avatar">
                {{ userInfo.adminName?.charAt(0) || 'A' }}
              </el-avatar>
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :on-change="handleAvatarChange"
                :auto-upload="false"
                accept="image/*"
              >
                <div class="upload-overlay">
                  <el-icon class="upload-icon"><Camera /></el-icon>
                  <span class="upload-text">更换头像</span>
                </div>
              </el-upload>
            </div>
            <div class="user-basic">
              <h3>{{ userInfo.adminName || '管理员' }}</h3>
              <p class="user-role">{{ roleText(userInfo.adminRole) }}</p>
              <el-tag :type="userInfo.adminStatus === 1 ? 'success' : 'danger'">
                {{ statusText(userInfo.adminStatus) }}
              </el-tag>
            </div>
          </div>
          
          <div class="info-details">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="管理员编号">{{ userInfo.adminNo || '-' }}</el-descriptions-item>
              <el-descriptions-item label="姓名">{{ userInfo.adminName || '-' }}</el-descriptions-item>
              <el-descriptions-item label="角色">{{ roleText(userInfo.adminRole) }}</el-descriptions-item>
              <el-descriptions-item label="状态">{{ statusText(userInfo.adminStatus) }}</el-descriptions-item>
              <el-descriptions-item label="手机号">{{ userInfo.adminPhone || '-' }}</el-descriptions-item>
              <el-descriptions-item label="邮箱">{{ userInfo.adminEmail || '-' }}</el-descriptions-item>
              <el-descriptions-item label="创建时间" :span="2">{{ formatDate(userInfo.createTime) }}</el-descriptions-item>
              <el-descriptions-item label="更新时间" :span="2">{{ formatDate(userInfo.updateTime) }}</el-descriptions-item>
              <el-descriptions-item label="备注" :span="2">{{ userInfo.adminRemark || '无' }}</el-descriptions-item>
            </el-descriptions>
          </div>
          
          <div class="action-buttons">
            <el-button type="primary" @click="handleEdit">
              <el-icon><Edit /></el-icon>编辑信息
            </el-button>
            <el-button @click="handleChangePassword">
              <el-icon><Lock /></el-icon>修改密码
            </el-button>
          </div>
        </div>

        <!-- 编辑表单 -->
        <div class="edit-form" v-else>
          <el-form ref="formRef" :model="editForm" :rules="rules" label-width="100px">
            <el-form-item label="管理员编号" prop="adminNo">
              <el-input v-model="editForm.adminNo" disabled />
            </el-form-item>
            <el-form-item label="姓名" prop="adminName">
              <el-input v-model="editForm.adminName" placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="手机号" prop="adminPhone">
              <el-input v-model="editForm.adminPhone" placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item label="邮箱" prop="adminEmail">
              <el-input v-model="editForm.adminEmail" placeholder="请输入邮箱" />
            </el-form-item>
            <el-form-item label="备注" prop="adminRemark">
              <el-input v-model="editForm.adminRemark" type="textarea" :rows="3" placeholder="请输入备注信息" />
            </el-form-item>
          </el-form>
          
          <div class="form-actions">
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="handleSave" :loading="saving">保存</el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="passwordDialogVisible" title="修改密码" width="400px">
      <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="100px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password placeholder="请输入原密码" />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password placeholder="请输入新密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password placeholder="请再次输入新密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePasswordSubmit" :loading="passwordSaving">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Lock, Camera } from '@element-plus/icons-vue'
import { getAdminDetail, updateAdmin } from '../api/admin'

// 用户信息
const userInfo = ref({})
const isEditing = ref(false)
const saving = ref(false)
const avatarUrl = ref('')

// 编辑表单
const editForm = reactive({
  adminId: null,
  adminNo: '',
  adminName: '',
  adminPhone: '',
  adminEmail: '',
  adminRemark: ''
})

// 表单验证规则
const rules = {
  adminName: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  adminPhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  adminEmail: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 密码修改
const passwordDialogVisible = ref(false)
const passwordSaving = ref(false)
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const formRef = ref()
const passwordFormRef = ref()

// 工具函数
const roleText = (role) => {
  if (role === 'super_admin') return '超级管理员'
  return '管理员'
}

const statusText = (status) => {
  if (status === 1) return '启用'
  if (status === 0) return '禁用'
  return status ?? '-'
}

const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit', 
    hour: '2-digit', 
    minute: '2-digit', 
    second: '2-digit' 
  })
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    // 这里应该从登录状态或localStorage获取当前用户ID
    // 暂时使用模拟数据
    const adminId = localStorage.getItem('adminId') || 1
    const response = await getAdminDetail(adminId)
    if (response.data) {
      userInfo.value = response.data
    } else {
      // 使用模拟数据
      userInfo.value = {
        adminId: 1,
        adminNo: 'admin001',
        adminName: '系统管理员',
        adminRole: 'admin',
        adminStatus: 1,
        adminPhone: '13800138000',
        adminEmail: 'admin@example.com',
        adminRemark: '系统管理员',
        createTime: new Date().toISOString(),
        updateTime: new Date().toISOString()
      }
    }
  } catch (error) {
    console.warn('获取管理员信息失败，使用模拟数据:', error)
    // 使用模拟数据
    userInfo.value = {
      adminId: 1,
      adminNo: 'admin001',
      adminName: '系统管理员',
      adminRole: 'admin',
      adminStatus: 1,
      adminPhone: '13800138000',
      adminEmail: 'admin@example.com',
      adminRemark: '系统管理员',
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString()
    }
  }
}

// 编辑信息
const handleEdit = () => {
  isEditing.value = true
  Object.keys(editForm).forEach(key => {
    editForm[key] = userInfo.value[key] || ''
  })
}

// 取消编辑
const handleCancel = () => {
  isEditing.value = false
  Object.keys(editForm).forEach(key => {
    editForm[key] = ''
  })
}

// 保存信息
const handleSave = async () => {
  const valid = await formRef.value.validate()
  if (!valid) return
  
  saving.value = true
  try {
    await updateAdmin(editForm)
    ElMessage.success('保存成功')
    isEditing.value = false
    await fetchUserInfo()
  } catch (error) {
    console.error('保存失败:', error)
  } finally {
    saving.value = false
  }
}

// 修改密码
const handleChangePassword = () => {
  passwordDialogVisible.value = true
  Object.keys(passwordForm).forEach(key => {
    passwordForm[key] = ''
  })
}

// 提交密码修改
const handlePasswordSubmit = async () => {
  const valid = await passwordFormRef.value.validate()
  if (!valid) return
  
  passwordSaving.value = true
  try {
    // 这里应该调用修改密码的API
    // await changePassword(passwordForm)
    ElMessage.success('密码修改成功')
    passwordDialogVisible.value = false
  } catch (error) {
    console.error('密码修改失败:', error)
  } finally {
    passwordSaving.value = false
  }
}

// 处理头像上传
const handleAvatarChange = (file) => {
  const isImage = file.raw.type.startsWith('image/')
  const isLt2M = file.raw.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return
  }

  // 预览图片
  const reader = new FileReader()
  reader.onload = (e) => {
    avatarUrl.value = e.target.result
    ElMessage.success('头像已更新（注意：需要点击"编辑信息"并保存才能永久保存）')
  }
  reader.readAsDataURL(file.raw)
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.admin-profile {
  background: #f5f7fa;
  padding: 20px;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  box-sizing: border-box;
}

.page-header {
  margin-bottom: 32px;
  text-align: center;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 28px;
  font-weight: 600;
  letter-spacing: 1px;
}

.profile-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  border: 1px solid #e4e7ed;
  background: #ffffff;
  overflow: hidden;
}

.profile-card :deep(.el-card__body) {
  padding: 40px;
}

.profile-content {
  max-width: 800px;
  margin: 0 auto;
}

.profile-info .avatar-section {
  display: flex;
  align-items: center;
  margin-bottom: 40px;
  padding-bottom: 30px;
  border-bottom: 1px solid #ebeef5;
}

.avatar-wrapper {
  position: relative;
  margin-right: 30px;
  cursor: pointer;
}

.avatar-wrapper:hover .upload-overlay {
  opacity: 1;
}

.avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-size: 48px;
  font-weight: bold;
}

.avatar-uploader {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.avatar-uploader :deep(.el-upload) {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  overflow: hidden;
}

.upload-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  opacity: 0;
  transition: opacity 0.3s;
  cursor: pointer;
}

.upload-icon {
  font-size: 32px;
  color: white;
  margin-bottom: 8px;
}

.upload-text {
  color: white;
  font-size: 14px;
  font-weight: 500;
}

.user-basic h3 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
}

.user-role {
  margin: 0 0 12px 0;
  color: #606266;
  font-size: 16px;
}

.info-details {
  margin-bottom: 40px;
}

.info-details :deep(.el-descriptions__header) {
  background: #f5f7fa;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
}

.edit-form {
  max-width: 600px;
  margin: 0 auto;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}
</style>











